"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 文件目录
Case Name   : 备节点删除表文件后重建备节点
Create At   : 2020/07/22
Owner       : @li-xin12345
Description :
    1、手动删除备机的表文件未删除主机的表文件
    2、重启主备机（主备机任意一台执行重启）
    3、主备机分别查询该表
    4、备数据库执行重建命令
Expect      :
   1、删除成功
   2、重启主备机成功
   3、主备机分别查询成功
   4、备机如果异常，重建备机
History     :
    modified:2020-12-14;删除表文件后，增加备机恢复等待时间，删除stop成功断言，只验证最终可以start成功；
    modified:2020-12-14;删除重建前备机表数据验证断言，只要备机build后，数据一致即可；teardown里增加是否重建校验
"""

import os
import sys
import unittest
import time
from yat.test import Node
from testcase.utils.CommonSH import *
from yat.test import macro

sys.path.append(sys.path[0] + "/../")
from testcase.utils.CommonSH import *
from testcase.utils.Common import Common
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger

logger = Logger()


class IndexFileDamaged(unittest.TestCase):
    commonshpri = CommonSH('PrimaryDbUser')
    commonshsta = CommonSH('Standby1DbUser')
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info('----------------------Opengauss_Reliability_Dbsys_Case190 start------------------------------------')
        self.dbPrimaryDbUser = Node(node='PrimaryDbUser')
        self.dbStandby1DbUser = Node(node='Standby1DbUser')
        self.Constant = Constant()
        self.common = Common('PrimaryRoot')
        self.tblname = 'reliability_dbsys_case190'
        self.tblpath = ''
        self.valuenum = 100000

    def test_Index_file_damaged(self):
        self.log.info('-------------------创建数据表，并插入数据-----------------------------------')
        result = self.common.createLargeNumTable(self.dbPrimaryDbUser, self.tblname, 1, self.valuenum)
        self.log.info(result)
        self.assertIn(self.Constant.CREATE_TABLE_SUCCESS, result)
        self.assertIn('INSERT 0 100000', result)

        self.log.info('----------------------------查询表文件路径----------------------')
        o_id = self.commonshpri.executDbSql(f'select oid from pg_class where relname=\'{self.tblname}\';')
        self.log.info(o_id)
        oid = o_id.splitlines()[-2]
        self.log.info(oid)
        result = self.commonshpri.executDbSql(f'Select pg_relation_filepath({oid}::regclass);')
        self.log.info(result)
        indexpath_tmp = result.splitlines()[-2].strip()
        self.tblpath = os.path.join(macro.DB_INSTANCE_PATH, indexpath_tmp)
        self.log.info(f'table path is: {self.tblpath}')

        self.log.info('------------------------waiting dirtypage update-------------------')
        result = self.commonshpri.check_whether_remain_dirty_page()
        self.assertTrue(result)

        self.log.info('----------------------------删除备节点表文件-----------------------------')
        excute_cmd = f'cp {self.tblpath} {self.tblpath}.testbak; rm -rf {self.tblpath}'
        self.log.info(excute_cmd)
        msg = self.dbStandby1DbUser.sh(excute_cmd).result()
        self.log.info(msg)

        self.log.info('-------------------重启数据库-------------------------------')
        time.sleep(60)
        self.log.info('查询数据库状态')
        status = self.commonshpri.getDbClusterStatus("status")
        self.log.info(status)
        self.commonshpri.stopDbCluster()
        result = self.commonshpri.startDbCluster()
        self.assertTrue(result)

        self.log.info('-------------------查询主数据库对应表数据-------------------')
        sql = f'select count(*) from {self.tblname};'
        result = self.commonshpri.executDbSql(sql)
        self.log.info(result)
        self.assertIn(str(self.valuenum), result)

        self.log.info('-------------------查询备数据库对应表数据-------------------')
        result = self.commonshsta.executDbSql(sql)
        self.log.info(result)

        self.log.info('------------------build standby------------------------')
        result = self.commonshsta.buildStandby()
        self.log.info(result)
        self.assertTrue(self.Constant.BUILD_SUCCESS_MSG, result)

        self.log.info('-------------------查询主备数据库对应表数据-------------------')
        sql = f'select count(*) from {self.tblname};'
        result = self.commonshpri.executDbSql(sql)
        self.log.info(result)
        self.assertIn(str(self.valuenum), result)
        result = self.commonshsta.executDbSql(sql)
        self.log.info(result)
        self.assertIn(str(self.valuenum), result)

    def tearDown(self):
        self.log.info('------------------this is tearDown------------------------')

        if self.commonshsta.check_whether_need_build():
            self.log.info('------------------need build standby------------------------')
            result = self.commonshsta.buildStandby()
            self.log.info(result)

        self.log.info('------------------drop table------------------------')
        result = self.commonshpri.executDbSql(f'drop table if exists {self.tblname} ;')
        self.log.info(result)
        self.log.info('----------------------------Reliability_Dbsys_Case190执行完成-----------------------------')
